package dao;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;

@Stateless(name = "DataAccess")
public class DataAccessBean implements DataAccess {

    private EntityManager entityManager;

    @PersistenceContext(unitName = "person-ds")
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public <T> T find(Class<T> type, Object id) {
        return entityManager.find(type, id);
    }

    @Override
    public <T> T add(T entity) {
        entityManager.persist(entity);
        return entity;
    }

    @Override
    public <T> T alter(T entity) {
        return entityManager.merge(entity);
    }

    @Override
    public <T> void remove(Class<T> type, Object id) {
        T entity = entityManager.find(type, id);
        if (entity != null) {
            entityManager.remove(entity);
        }
    }

    @Override
    public <T> List<T> findAll(Class<T> type) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> query = cb.createQuery(type);
        Root<T> tRoot = query.from(type);
        query.select(tRoot);
        return entityManager.createQuery(query).getResultList();
    }

    @Override
    public <T> List<T> findByCriteria(Class<T> type, Map<String, Object> params) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> query = cb.createQuery(type);
        Root<T> tRoot = query.from(type);
        query.select(tRoot);

        for (Map.Entry<String, Object> entry : params.entrySet()) {
          query.where(tRoot.get(entry.getKey()).in(entry.getValue()));
        }

        return entityManager.createQuery(query).getResultList();
    }

}
